package org.example.cet.demos.controller;

import cn.hutool.core.util.ObjectUtil;
import org.example.cet.demos.domain.Result;
import org.example.cet.demos.exception.CommonException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {
    @PostMapping("/file")
    public Result upload(MultipartFile file) throws IOException {
        if (ObjectUtil.isNull(file)) throw new CommonException(500,"文件为空");
//        if (!img.getContentType().equals("image/jpeg") && !img.getContentType().equals("image/png")) throw new SaTokenException(ResultCodeEnum.PARAM_IMG_ERROR.getCode(),ResultCodeEnum.PARAM_IMG_ERROR.getMsg());
        String originalFilename = file.getOriginalFilename();
        System.out.println(file.getSize());
        int i = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(i);
        String uuidName = UUID.randomUUID() + extname;
        String rootPath = System.getProperty("user.dir");
        System.out.println(rootPath);
        file.transferTo(new File(rootPath + "/src/main/resources/static/file/" + uuidName));
        return Result.success("http://localhost:8080/file/"+uuidName);
    }
}
